'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports ua
Imports System.IO
Imports System.Net.Mail

Public Class frmConfiguration
    Public ChangeMade As Boolean = False
    Private AppDataPath As String = GetAppDataPath()
    Private ISPFormAdded As Boolean = False
    Private NewConfigurationData As New ConfigurationData
    Private ISPReturnData As ISPReturnData
    Private ImageWidth As Integer
    Private ImageHeight As Integer

    Private Sub frmConfiguration_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'already running, exit
        Dim myProcesses As Process() = Process.GetProcessesByName("UAConfiguration")
        If myProcesses.Length > 1 Then End
        myProcesses = Nothing

        If UnixDetected() = False Then
            grbUnixCommand.Visible = False

            If System.Globalization.CultureInfo.CurrentCulture.Name <> "en-AU" Then
                Dim DR As DialogResult = MessageBox.Show("Your regional settings are not set to Australia. This may affect Usage Agent. Do you want to set this now?", "Usage Agent", MessageBoxButtons.YesNo)
                If DR = Windows.Forms.DialogResult.Yes Then
                    System.Diagnostics.Process.Start("control.exe", "international")
                    End
                End If
            End If
        End If

        If UnixDetected() = True Then
            'hide windows specific items
            chkIconWindowsStartup.Visible = False
            chkWallpaperWindowsStartup.Visible = False

            chkRetrieveNICData.Checked = False
            chkRetrieveNICData.Enabled = False

            lstOption.Items.RemoveAt(lstOption.Items.IndexOf("Network Card"))

            grbNicGraph.Visible = False
            chkIconWindowsStartup.Checked = False
            chkIconWindowsStartup.Visible = False
            chkShowNICGraph.Checked = False
            chkShowNICGraph.Visible = False
            chkIconNicGraph.Checked = False
            chkIconNicGraph.Visible = False
            chkShowNICStats.Checked = False
            chkShowNICStats.Visible = False
        End If

        If VistaDetected() = False Then
            'hide vista specific items
            lstOption.Items.RemoveAt(lstOption.Items.IndexOf("Vista Gadget"))
        End If

        'enable tcp performance if currently disabled
        RegEnablePerfCounter()

        'add ISP's
        ComboAddISP(cboISP)

        If UnixDetected() = False Then
            'add network cards
            Try
                Dim category As PerformanceCounterCategory
                Dim name As String
                category = New PerformanceCounterCategory("Network Interface")
                For Each name In category.GetInstanceNames()
                    If name.Contains("Loopback interface") = False Then
                        cboNIC.Items.Add(name)
                    End If
                Next

            Catch ex1 As System.NotImplementedException
                chkRetrieveNICData.Checked = False
                chkRetrieveNICData.Enabled = False
                MessageBox.Show("Network card support is not yet available on this platform. Disabling NIC Monitoring.", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Catch ex As Exception
                chkRetrieveNICData.Checked = False
                chkRetrieveNICData.Enabled = False
                MessageBox.Show("There was an error attempting to find your Networks Card(s). Disabling NIC Monitoring. If your running MS Vista with User Account Protection enabled, you may need to make the current user a member of the ""Performance Monitors Users"" group.", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try
        End If

        'add intervals to combos
        Dim x As Integer
        cboUpdateDelay.Items.Add(0)
        For x = 5 To 60
            cboUpdateDelay.Items.Add(x)
            cboUpdateInterval.Items.Add(x)
        Next
        cboUpdateDelay.SelectedIndex = 0

        For x = 120 To (60 * 12) Step 60
            cboUpdateInterval.Items.Add(x)
        Next
        cboUpdateInterval.SelectedIndex = 19

        For Each NewFontFamily As FontFamily In System.Drawing.FontFamily.Families
            cboFont.Items.Add(NewFontFamily.Name)
            If NewFontFamily.Name = "Verdana" Then cboFont.Text = "Verdana"
        Next NewFontFamily

        'set default values
        cboConnectionType.SelectedIndex = 0
        cboPeakUnlimited.SelectedIndex = 0
        cboPeakReached.SelectedIndex = 0
        cboOffpeakAvailable.SelectedIndex = 1
        cboOffpeakTimeZone.SelectedIndex = 0
        cboOffpeakUnlimited.SelectedIndex = 0
        cboOffpeakWeekendsUnlimited.SelectedIndex = 0
        cboOffpeakReached.SelectedIndex = 1
        cboOffpeakAvailableAfterPeakReached.SelectedIndex = 1
        cboUploadCounted.SelectedIndex = 0
        cboUploadAvailable.SelectedIndex = 0
        cboWAIXAvailable.SelectedIndex = 0
        cboExcessApplicable.SelectedIndex = 0
        cboRolloverDay.SelectedIndex = 0
        cboFontSize.SelectedIndex = 0

        Try
            If My.Computer.FileSystem.DirectoryExists(AppDataPath) = False Then
                My.Computer.FileSystem.CreateDirectory(AppDataPath)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End
        End Try

        'load configuration
        Dim RetVal As Boolean = LoadConfiguration(NewConfigurationData)

        'populate controls

        'Application Update
        chkCheckVersionOnStartup.Checked = NewConfigurationData.CheckVersionOnStartup
        chkSendStats.Checked = NewConfigurationData.SendStats

        'ISP
        If cboISP.FindStringExact(NewConfigurationData.ISPName) <> -1 Then
            cboISP.SelectedIndex = cboISP.FindStringExact(NewConfigurationData.ISPName)
        Else
            cboISP.SelectedIndex = 0
        End If
        txtUsername.Text = NewConfigurationData.Username
        txtPassword.Text = NewConfigurationData.Password
        cboConnectionType.Text = NewConfigurationData.ISPConnectionType
        txtServiceNo.Text = NewConfigurationData.ISPServiceNo

        'ISP Plan
        cboPeakUnlimited.SelectedIndex = Math.Abs(CInt(NewConfigurationData.PeakUnlimited))
        txtPeakLimit.Text = NewConfigurationData.PeakUsageLimit
        cboPeakReached.Text = NewConfigurationData.PeakReached
        cboOffpeakAvailable.SelectedIndex = Math.Abs(CInt(NewConfigurationData.OffpeakAvailable))
        txtOffpeakStartHour.Text = NewConfigurationData.OffpeakStartHour
        txtOffpeakEndHour.Text = NewConfigurationData.OffpeakEndHour
        cboOffpeakTimeZone.Text = NewConfigurationData.OffpeakTimeZone
        cboOffpeakUnlimited.SelectedIndex = Math.Abs(CInt(NewConfigurationData.OffpeakUnlimited))
        txtOffpeakLimit.Text = NewConfigurationData.OffpeakUsageLimit
        cboOffpeakWeekendsUnlimited.SelectedIndex = Math.Abs(CInt(NewConfigurationData.OffpeakWeekendsUnlimited))
        cboOffpeakReached.Text = NewConfigurationData.OffpeakReached
        cboOffpeakAvailableAfterPeakReached.SelectedIndex = Math.Abs(CInt(NewConfigurationData.OffpeakAvailableAfterPeakReached))
        cboUploadCounted.SelectedIndex = Math.Abs(CInt(NewConfigurationData.UploadCounted))
        cboUploadAvailable.SelectedIndex = Math.Abs(CInt(NewConfigurationData.UploadAvailable))
        cboWAIXAvailable.SelectedIndex = Math.Abs(CInt(NewConfigurationData.WAIXAvailable))
        cboExcessApplicable.SelectedIndex = Math.Abs(CInt(NewConfigurationData.ExcessApplicable))
        txtExcessRate.Text = NewConfigurationData.ExcessRate
        txtExcessMaxCharge.Text = NewConfigurationData.ExcessMaxCharge
        cboRolloverDay.Text = NewConfigurationData.RolloverDay

        'Network Card
        If cboNIC.Items.Count > 0 Then
            chkRetrieveNICData.Checked = NewConfigurationData.RetrieveNICData
        End If
        If cboNIC.Items.Count > 0 Then
            If cboNIC.FindStringExact(NewConfigurationData.NICName) <> -1 Then
                cboNIC.SelectedIndex = cboNIC.FindStringExact(NewConfigurationData.NICName)
            Else
                cboNIC.SelectedIndex = 0
            End If
        End If

        'Update Interval
        If cboUpdateInterval.FindStringExact(NewConfigurationData.UpdateInterval.ToString) <> -1 Then
            cboUpdateInterval.SelectedIndex = cboUpdateInterval.FindStringExact(NewConfigurationData.UpdateInterval.ToString)
        Else
            cboUpdateInterval.SelectedIndex = 19
        End If

        'Proxy
        If NewConfigurationData.ProxyConnect = CBool("True") Then
            rdbProxy.Checked = True
        Else
            rdbDirect.Checked = True
        End If
        txtProxyName.Text = NewConfigurationData.ProxyName
        txtProxyPort.Text = NewConfigurationData.ProxyPort
        txtProxyLogin.Text = NewConfigurationData.ProxyLogin
        txtProxyPassword.Text = NewConfigurationData.ProxyPassword

        'Logging
        chkEnableLogging.Checked = NewConfigurationData.LogEnabled

        'Data Export
        chkExportTextLog.Checked = NewConfigurationData.ExportTextLog
        chkExportDescriptors.Checked = NewConfigurationData.ExportDescriptors
        chkExportNotations.Checked = NewConfigurationData.ExportNotations
        chkExportDownload.Checked = NewConfigurationData.ExportDownload
        chkExportRemaining.Checked = NewConfigurationData.ExportRemaining
        chkExportAverage.Checked = NewConfigurationData.ExportAverage
        chkExportAverageRemaining.Checked = NewConfigurationData.ExportAverageRemaining
        chkExportPlanLimit.Checked = NewConfigurationData.ExportPlanLimit
        chkExportShaped.Checked = NewConfigurationData.ExportShaped
        chkExportTime.Checked = NewConfigurationData.ExportTime
        chkExportUpload.Checked = NewConfigurationData.ExportUpload
        txtExportPath.Text = NewConfigurationData.ExportPath

        'Image Export
        chkExportImage.Checked = NewConfigurationData.ExportImage
        chkExportHTML.Checked = NewConfigurationData.ExportHTML
        chkExportLocalHTMLPath.Checked = NewConfigurationData.ExportLocalHTMLPath
        txtExportImagePath.Text = NewConfigurationData.ExportImagePath

        'Alerts
        chkEnableAlerts.Checked = NewConfigurationData.AlertEnable
        chkAlertDialog.Checked = NewConfigurationData.AlertDialog
        chkAlertEmail.Checked = NewConfigurationData.AlertEmail
        lstAlert.Items.Clear()
        For Each AlertValue As String In NewConfigurationData.AlertValue.Items
            lstAlert.Items.Add(AlertValue)
        Next
        txtMailTo.Text = NewConfigurationData.AlertMailTo
        txtMailServer.Text = NewConfigurationData.AlertMailServer

        'Display
        For Each FontName As String In cboFont.Items
            If FontName = NewConfigurationData.Font Then
                cboFont.Text = NewConfigurationData.Font
                Exit For
            End If
        Next
        If cboFont.Text = "" Then cboFont.SelectedIndex = 0

        cboFontSize.Text = NewConfigurationData.FontSize.ToString
        If Val(NewConfigurationData.Opacity) = 0 Then
            cboOpacity.Text = 100 & "%"
        Else
            cboOpacity.Text = Val(NewConfigurationData.Opacity) * 100 & "%"
        End If
        chkShowISPGraph.Checked = NewConfigurationData.ShowISPGraph
        chkShowISPStats.Checked = NewConfigurationData.ShowISPStats
        chkShowNICStats.Checked = NewConfigurationData.ShowNICStats
        lstUsageColourValue.Items.Clear()
        For Each NewObject As Object In NewConfigurationData.IconISPUsageColourValue.Items
            lstUsageColourValue.Items.Add(NewObject)
        Next
        chkShowBackground.Checked = NewConfigurationData.ShowBackground
        pbxBackgroundColour.BackColor = Color.FromArgb(CInt(NewConfigurationData.BackColour))
        pbxForegroundColour.BackColor = Color.FromArgb(CInt(NewConfigurationData.ForeColour))

        'UA Icon
        chkIconWindowsStartup.Checked = NewConfigurationData.IconWindowsStartup
        If cboUpdateDelay.FindStringExact(NewConfigurationData.IconUpdateDelay.ToString) <> -1 Then
            cboUpdateDelay.SelectedIndex = cboUpdateDelay.FindStringExact(NewConfigurationData.IconUpdateDelay.ToString)
        Else
            cboUpdateDelay.SelectedIndex = 0
        End If
        chkStatsShowStartup.Checked = NewConfigurationData.IconStatsShowStartup
        chkShowNICGraph.Checked = NewConfigurationData.IconShowNICGraph
        chkTopMost.Checked = NewConfigurationData.IconStatsTopmost
        txtXPos.Text = NewConfigurationData.IconStartX.ToString
        txtYPos.Text = NewConfigurationData.IconStartY.ToString
        txtCapacityDown.Text = NewConfigurationData.IconNICCapacityDown.ToString
        txtCapacityUp.Text = NewConfigurationData.IconNICCapacityUp.ToString
        chkIconISPUsage.Checked = NewConfigurationData.IconTrayISPUsage
        chkIconISPColour.Checked = NewConfigurationData.IconTrayISPColour
        chkIconNicGraph.Checked = NewConfigurationData.IconTrayNICGraph

        'UA Wallpaper
        chkWallpaperEnable.Checked = NewConfigurationData.WallpaperEnable
        chkWallpaperWindowsStartup.Checked = NewConfigurationData.WallpaperWindowsStartup
        For Each NewWallpaperFormData As WallpaperFormData In NewConfigurationData.WallpaperFormList
            lstForm.Items.Add(NewWallpaperFormData)
            'disable add isp form button
            If NewWallpaperFormData.FormType = 0 Then btnAddISPForm.Enabled = False
        Next
        txtWallpaperUnixCommand.Text = NewConfigurationData.WallpaperUnixCommand
        txtWallpaperUnixCommandArgs.Text = NewConfigurationData.WallpaperUnixCommandArgs

        'set UAWallpaper buttons
        chkWallpaperEnable_CheckedChanged(Nothing, Nothing)

        'vista gadget
        chkEnableVistaGadget.Checked = NewConfigurationData.VistaGadgetEnable

        lstOption.SelectedIndex = 0
    End Sub

    Private Sub btnAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAbout.Click
        Dim frmAbout As New frmAbout
        frmAbout.ShowDialog()
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If SaveCurrentConfiguration() = True Then MessageBox.Show("Configuration Saved!", "Usage Agent Configuration", MessageBoxButtons.OK, MessageBoxIcon.Information)
        ChangeMade = False
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        If ChangeMade = True Then
            Dim Retval As DialogResult = MessageBox.Show("Your changes have not been saved. Continue exit?", "Usage Agent", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If Retval = Windows.Forms.DialogResult.No Then Exit Sub
        End If

        If NewConfigurationData.ISPValidated = False Then
            Dim Retval As DialogResult = MessageBox.Show("The connection to your ISP has not been validated. You must validate prior to running Usage Agent. Validate now?", "Usage Agent", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If Retval = Windows.Forms.DialogResult.Yes Then
                NewConfigurationData.Alert1Count = 0
                NewConfigurationData.Alert2Count = 0
                NewConfigurationData.Alert3Count = 0
                NewConfigurationData.Alert4Count = 0
                NewConfigurationData.Alert5Count = 0
                If ValidateGeneral() = False Then Exit Sub
                MessageBox.Show("Settings have been validated", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If

        'if usage agent icon is open, restart it
        Dim myProcesses As Process() = Process.GetProcessesByName("UATrayIcon")
        If myProcesses.Length > 0 Then
            'close ua
            myProcesses(0).Kill()

            'wait for a second
            System.Threading.Thread.Sleep(500)

            'apply changes
            If UnixDetected() = False Then
                NewShell(Application.StartupPath, Application.StartupPath & Path.DirectorySeparatorChar & "uatrayicon.exe", "", False)
            Else
                NewShell(Application.StartupPath, "mono", "uatrayicon.exe", False)
            End If
        End If
        myProcesses = Nothing

        Me.Close()
    End Sub

    Function ValidateGeneral(Optional ByVal SaveConfig As Boolean = True) As Boolean
        NewConfigurationData.ISPValidated = False
        ValidateGeneral = False

        '################# pnlISP

        If cboISP.Text = "" Then
            MessageBox.Show("ISP Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "ISP"
            cboISP.Focus()
            Exit Function
        End If

        If txtUsername.Text = "" Then
            MessageBox.Show("Login Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "ISP"
            txtUsername.Focus()
            Exit Function
        End If

        If txtPassword.Text = "" Then
            MessageBox.Show("Password Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "ISP"
            txtPassword.Focus()
            Exit Function
        End If

        If txtServiceNo.Visible = True Then
            If txtServiceNo.Text = "" Then
                MessageBox.Show("Service Number Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "ISP"
                txtServiceNo.Focus()
                Exit Function
            End If
        End If

        '###################### pnlISPPlan

        If cboPeakUnlimited.Text = "No" Then
            If txtPeakLimit.Text = "" Then
                MessageBox.Show("Peak Limit Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "ISP Plan"
                txtPeakLimit.Focus()
                Exit Function
            Else
                txtPeakLimit.Text = CInt(Val(txtPeakLimit.Text)).ToString
                If Val(txtPeakLimit.Text) < 10 Then
                    MessageBox.Show("Peak Limit Required in Megabytes", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    lstOption.SelectedItem = "ISP Plan"
                    txtPeakLimit.Focus()
                    Exit Function
                End If
            End If
        End If

        If cboOffpeakAvailable.Text = "Yes" Then
            If txtOffpeakStartHour.Text = "" Or Val(txtOffpeakStartHour.Text) < 0 Or Val(txtOffpeakStartHour.Text) >= 24 Then
                MessageBox.Show("Valid Offpeak Start Time Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "ISP Plan"
                txtOffpeakStartHour.Focus()
                Exit Function
            Else
                txtOffpeakStartHour.Text = CInt(Val(txtOffpeakStartHour.Text)).ToString
            End If

            If txtOffpeakEndHour.Text = "" Or Val(txtOffpeakEndHour.Text) < 0 Or Val(txtOffpeakEndHour.Text) >= 24 Then
                MessageBox.Show("Valid Offpeak End Time Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "ISP Plan"
                txtOffpeakEndHour.Focus()
                Exit Function
            Else
                txtOffpeakEndHour.Text = CInt(Val(txtOffpeakEndHour.Text)).ToString
            End If

            If cboOffpeakUnlimited.Text = "No" Then
                If txtOffpeakLimit.Text = "" Then
                    MessageBox.Show("Offpeak Limit Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    lstOption.SelectedItem = "ISP Plan"
                    txtOffpeakLimit.Focus()
                    Exit Function
                Else
                    txtOffpeakLimit.Text = CInt(Val(txtOffpeakLimit.Text)).ToString
                    If Val(txtOffpeakLimit.Text) < 10 Then
                        MessageBox.Show("Offpeak Limit Required in Megabytes", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                        lstOption.SelectedItem = "ISP Plan"
                        txtOffpeakLimit.Focus()
                        Exit Function
                    End If
                End If
            End If
        End If

        If cboExcessApplicable.Text = "Yes" Then
            If txtExcessRate.Text = "" Or Val(txtExcessRate.Text) <= 0 Then
                MessageBox.Show("Valid Excess Rate Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "ISP Plan"
                txtExcessRate.Focus()
                Exit Function
            End If

            If txtExcessMaxCharge.Text = "" Or Val(txtExcessMaxCharge.Text) <= 0 Then
                MessageBox.Show("Valid Maximum Excess Charge Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "ISP Plan"
                txtExcessMaxCharge.Focus()
                Exit Function
            End If
        End If

        If cboRolloverDay.Text = "" Or Val(cboRolloverDay.Text) < 1 Or Val(cboRolloverDay.Text) > 31 Then
            MessageBox.Show("Valid Rollover Day Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "ISP Plan"
            cboRolloverDay.Focus()
            Exit Function
        End If

        '######################### pnlNIC

        If chkRetrieveNICData.Checked = True Then
            If cboNIC.Text = "" Then
                MessageBox.Show("NIC Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "Network Card"
                cboNIC.Focus()
                Exit Function
            End If
        End If

        'check connection
        If rdbProxy.Checked = True Then
            If txtProxyName.Text = "" Then
                MessageBox.Show("HTTP PROXY Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "Proxy"
                txtProxyName.Focus()
                Exit Function
            End If

            If txtProxyPort.Text = "" Then
                MessageBox.Show("PROXY PORT Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "Proxy"
                txtProxyPort.Focus()
                Exit Function
            End If

            If TestIsNumeric(txtProxyPort.Text) = False Then
                MessageBox.Show("Invalid PROXY PORT", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                lstOption.SelectedItem = "Proxy"
                txtProxyPort.Focus()
                Exit Function
            End If
        End If

        If cboUpdateInterval.Text = "" Then
            MessageBox.Show("Update Interval Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "Update Interval"
            cboUpdateInterval.Focus()
            Exit Function
        End If

        If Me.chkIconISPColour.Checked = True And lstUsageColourValue.Items.Count = 0 Then
            MessageBox.Show("ISP Usage Colour Value Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "Display"
            lstUsageColourValue.Focus()
            Exit Function
        End If

        If cboFont.Text = "" Then
            MessageBox.Show("FONT Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "Display"
            cboFont.Focus()
            Exit Function
        End If

        If cboOpacity.Text = "" Then
            MessageBox.Show("FORM OPACITY Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "Display"
            cboOpacity.Focus()
            Exit Function
        End If

        If chkShowISPGraph.Checked = False And chkShowISPStats.Checked = False And chkShowNICStats.Checked = False Then
            MessageBox.Show("At least ONE form object must be shown", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            lstOption.SelectedItem = "Display"
            chkShowISPGraph.Focus()
            Exit Function
        End If

        'connect to ISP 
        Me.Cursor = Cursors.WaitCursor
        If SaveConfig = True Then SaveCurrentConfiguration()
        ISPReturnData = New ISPData(NewConfigurationData).ISPReturnData
        Me.Cursor = Cursors.Default

        If ISPReturnData.Status <> 2 Or ISPReturnData.ErrorMessage <> "" Then
            MessageBox.Show(ISPReturnData.ErrorMessage, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Function
        Else
            'save isp data into config
            NewConfigurationData.ISPValidated = True
            If SaveConfig = True Then SaveCurrentConfiguration()
        End If

        ValidateGeneral = True

    End Function

    Function ValidateIcon() As Boolean
        ValidateIcon = False
        If chkRetrieveNICData.Checked = True Then
            If Val(txtCapacityDown.Text) < 1 Then
                MessageBox.Show("Valid Download Capacity Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtCapacityDown.Focus()
                Exit Function
            End If

            If Val(txtCapacityUp.Text) < 1 Then
                MessageBox.Show("Valid Upload Capacity Required", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtCapacityUp.Focus()
                Exit Function
            End If
        End If

        ValidateIcon = True
    End Function

    Private Sub cboISP_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboISP.SelectedIndexChanged

        If CType(cboISP.SelectedItem, ISP).Name = "ComCen" Or CType(cboISP.SelectedItem, ISP).Name = "Spin" Then
            lblConnectionType.Visible = True
            cboConnectionType.Visible = True
            lblServiceNo.Visible = True
            txtServiceNo.Visible = True
        Else
            lblConnectionType.Visible = False
            cboConnectionType.Visible = False
            lblServiceNo.Visible = False
            txtServiceNo.Visible = False
        End If

        If cboISP.Visible = True Then NewConfigurationData.ISPValidated = False
    End Sub

    Private Sub chkRetrieveNICData_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkRetrieveNICData.CheckedChanged
        If chkRetrieveNICData.Checked = True Then
            'enable options
            cboNIC.Enabled = True
            chkIconNicGraph.Enabled = True
            EnableControlChildren(grbNicGraph)
            If chkEnableLogging.Checked = True Then
                chkShowNICStats.Enabled = True
            Else
                chkShowNICStats.Enabled = False
            End If
        Else
            'disable options
            cboNIC.Enabled = False
            chkIconNicGraph.Enabled = False
            DisableControlChildren(grbNicGraph)
            chkShowNICStats.Enabled = False
        End If
    End Sub

    Private Sub rdbProxy_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbProxy.CheckedChanged
        If rdbProxy.Checked = False Then
            lblProxyName.Enabled = False
            lblProxyPort.Enabled = False
            lblProxyLogin.Enabled = False
            lblProxyPassword.Enabled = False
            txtProxyLogin.Enabled = False
            txtProxyName.Enabled = False
            txtProxyPassword.Enabled = False
            txtProxyPort.Enabled = False
        Else
            lblProxyName.Enabled = True
            lblProxyPort.Enabled = True
            lblProxyLogin.Enabled = True
            lblProxyPassword.Enabled = True
            txtProxyLogin.Enabled = True
            txtProxyName.Enabled = True
            txtProxyPassword.Enabled = True
            txtProxyPort.Enabled = True
        End If
    End Sub

    Private Sub chkExportTextLog_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkExportTextLog.CheckedChanged
        If chkExportTextLog.Checked = True Then
            chkExportDescriptors.Enabled = True
            chkExportNotations.Enabled = True
            EnableControlChildren(grbExport)
            EnableControlChildren(grbExportPath)
        Else
            chkExportDescriptors.Enabled = False
            chkExportNotations.Enabled = False
            DisableControlChildren(grbExport)
            DisableControlChildren(grbExportPath)
            chkExportTextLog.Enabled = True
        End If
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        If lstUsageColourValue.SelectedIndex = -1 Then Exit Sub

        Dim frmColourValue As New frmColourValue
        frmColourValue.EditFlag = True
        frmColourValue.FormParent = Me
        frmColourValue.txtPercentage.Text = CType(lstUsageColourValue.SelectedItem, UsageColourValue).Percentage.ToString
        frmColourValue.ColourValue = CType(lstUsageColourValue.SelectedItem, UsageColourValue).Value
        frmColourValue.pbxColour.BackColor = Color.FromArgb(CInt(CType(lstUsageColourValue.SelectedItem, UsageColourValue).Value))
        frmColourValue.ShowDialog()
        frmColourValue.Dispose()
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If lstUsageColourValue.SelectedIndex = -1 Then Exit Sub

        lstUsageColourValue.Items.RemoveAt(lstUsageColourValue.SelectedIndex)

        If lstUsageColourValue.Items.Count > 0 Then
            lstUsageColourValue.SelectedIndex = 0
        End If
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim frmColourValue As New frmColourValue
        frmColourValue.EditFlag = False
        frmColourValue.FormParent = Me
        frmColourValue.ShowDialog()
        frmColourValue.Dispose()
    End Sub

    Private Sub btnDefault_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDefault.Click
        Dim Retval As DialogResult = MessageBox.Show("Are you sure you want to replace the existing colours with the default values?", "Usage Agent", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If Retval = Windows.Forms.DialogResult.Yes Then
            SetDefaultUsageColourValue(lstUsageColourValue)
            lstUsageColourValue.Refresh()
        End If
        lstUsageColourValue.SelectedIndex = 0
    End Sub

    Private Sub lstUsageColourValue_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstUsageColourValue.DoubleClick
        btnEdit_Click(Nothing, Nothing)
    End Sub

    Private Sub btnBackgroundColour_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackgroundColour.Click
        ColorDialog1.Color = pbxBackgroundColour.BackColor
        Dim RetVal As DialogResult = ColorDialog1.ShowDialog()
        If RetVal = Windows.Forms.DialogResult.OK Then
            pbxBackgroundColour.BackColor = ColorDialog1.Color
        End If
    End Sub

    Private Sub btnForegroundColour_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForegroundColour.Click
        ColorDialog1.Color = pbxForegroundColour.BackColor
        Dim RetVal As DialogResult = ColorDialog1.ShowDialog()
        If RetVal = Windows.Forms.DialogResult.OK Then
            pbxForegroundColour.BackColor = ColorDialog1.Color
        End If
    End Sub

    Private Sub btnGenerateImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateImage.Click
        If SaveCurrentConfiguration() = False Then Exit Sub

        'apply changes
        If UnixDetected() = False Then
            NewShell(Application.StartupPath, Application.StartupPath & Path.DirectorySeparatorChar & "uaimage.exe", "", False)
        Else
            NewShell(Application.StartupPath, "mono", "uaimage.exe", False)
        End If
    End Sub

    Private Sub btnValidateDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidateDisplay.Click
        'general tab
        If ValidateGeneral() = False Then Exit Sub

        MessageBox.Show("Settings have been validated", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub chkShowBackground_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkShowBackground.CheckedChanged
        If chkShowBackground.Checked = False Then
            'enable options
            Label14.Enabled = False
            pbxBackgroundColour.Enabled = False
            btnBackgroundColour.Enabled = False
        Else
            'disable options
            Label14.Enabled = True
            pbxBackgroundColour.Enabled = True
            btnBackgroundColour.Enabled = True
        End If
    End Sub

    Private Sub chkEnableLogging_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkEnableLogging.CheckedChanged
        chkExportTextLog.Enabled = False
        chkExportDescriptors.Enabled = False
        chkExportNotations.Enabled = False
        DisableControlChildren(grbExport)
        DisableControlChildren(grbExportPath)

        If chkEnableLogging.Checked = True Then
            If chkRetrieveNICData.Checked = True Then
                chkShowNICStats.Enabled = True
            Else
                chkShowNICStats.Enabled = False
            End If
            chkExportTextLog.Enabled = True
            If chkExportTextLog.Checked = True Then
                chkExportTextLog.Enabled = True
                chkExportDescriptors.Enabled = True
                chkExportNotations.Enabled = True
                EnableControlChildren(grbExport)
                EnableControlChildren(grbExportPath)
            Else
                chkExportDescriptors.Enabled = False
                chkExportNotations.Enabled = False
                DisableControlChildren(grbExport)
                DisableControlChildren(grbExportPath)
                chkExportTextLog.Enabled = True
            End If
        Else
            chkShowNICStats.Enabled = False
        End If
    End Sub

    Private Sub btnAddISPForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddISPForm.Click
        'only add form if ISP settings are valid
        If ValidateGeneral() = False Then Exit Sub

        Dim FormSize As Point = CalculateFormSize(NewConfigurationData, ISPReturnData)

        Dim frmAdd As New frmAdd
        frmAdd.EditFlag = False
        frmAdd.FormParent = Me
        frmAdd.FormType = 0
        frmAdd.txtFormWidth.Text = FormSize.X.ToString
        frmAdd.txtFormHeight.Text = FormSize.Y.ToString
        frmAdd.ShowDialog()
        frmAdd.Dispose()
    End Sub

    Private Sub btnAddWebForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddWebForm.Click
        Dim frmAdd As New frmAdd
        frmAdd.EditFlag = False
        frmAdd.FormParent = Me
        frmAdd.FormType = 1
        frmAdd.ShowDialog()
        frmAdd.Dispose()
    End Sub

    Private Sub btnEditForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditForm.Click
        If lstForm.SelectedIndex = -1 Then Exit Sub

        Dim frmAdd As New frmAdd
        frmAdd.EditFlag = True
        frmAdd.FormParent = Me

        If CType(lstForm.SelectedItem, WallpaperFormData).FormType = 0 Then
            'only edit form if ISP settings are valid
            If ValidateGeneral() = False Then Exit Sub

            frmAdd.FormType = 0
            'load configuration
            LoadConfiguration(NewConfigurationData)

            'save size values
            NewConfigurationData.ShowISPGraph = chkShowISPGraph.Checked
            NewConfigurationData.ShowISPStats = chkShowISPStats.Checked
            NewConfigurationData.RetrieveNICData = chkRetrieveNICData.Checked
            NewConfigurationData.ShowNICStats = chkShowNICStats.Checked

            Dim FormSize As Point = CalculateFormSize(NewConfigurationData, ISPReturnData)

            frmAdd.txtFormWidth.Text = FormSize.X.ToString
            frmAdd.txtFormHeight.Text = FormSize.Y.ToString
        Else
            frmAdd.FormType = 1
            frmAdd.chkShowLabel.Checked = CType(lstForm.SelectedItem, WallpaperFormData).ShowLabel
            frmAdd.txtLabel.Text = CType(lstForm.SelectedItem, WallpaperFormData).Label
            frmAdd.txtImageURL.Text = CType(lstForm.SelectedItem, WallpaperFormData).URL
            frmAdd.chkImageStretch.Checked = CType(lstForm.SelectedItem, WallpaperFormData).StretchImage
            frmAdd.chkImageAspectRatio.Checked = CType(lstForm.SelectedItem, WallpaperFormData).MaintainAspectRatio
            frmAdd.chkImageZoom.Checked = CType(lstForm.SelectedItem, WallpaperFormData).Zoom
            frmAdd.txtZoomX.Text = CType(lstForm.SelectedItem, WallpaperFormData).ZoomX
            frmAdd.txtZoomY.Text = CType(lstForm.SelectedItem, WallpaperFormData).ZoomY
            frmAdd.txtZoomWidth.Text = CType(lstForm.SelectedItem, WallpaperFormData).ZoomWidth
            frmAdd.txtZoomHeight.Text = CType(lstForm.SelectedItem, WallpaperFormData).ZoomHeight
            frmAdd.chkShowBackground.Checked = CType(lstForm.SelectedItem, WallpaperFormData).ShowBackground
            frmAdd.pbxBackgroundColour.BackColor = Color.FromArgb(CInt(CType(lstForm.SelectedItem, WallpaperFormData).BackColour))
            frmAdd.pbxForegroundColour.BackColor = Color.FromArgb(CInt(CType(lstForm.SelectedItem, WallpaperFormData).ForeColour))
            frmAdd.txtOpacity.Text = CType(lstForm.SelectedItem, WallpaperFormData).Opacity
            frmAdd.txtFormWidth.Text = CType(lstForm.SelectedItem, WallpaperFormData).Width
            frmAdd.txtFormHeight.Text = CType(lstForm.SelectedItem, WallpaperFormData).Height
        End If

        frmAdd.txtX.Text = CType(lstForm.SelectedItem, WallpaperFormData).X
        frmAdd.txtY.Text = CType(lstForm.SelectedItem, WallpaperFormData).Y

        frmAdd.ShowDialog()
        frmAdd.Dispose()
    End Sub

    Private Sub btnDeleteForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteForm.Click
        If lstForm.SelectedIndex = -1 Then Exit Sub

        lstForm.Items.RemoveAt(lstForm.SelectedIndex)

        'check if there is an ISP entry
        Dim ISPFound As Boolean = False
        For Each FormData As WallpaperFormData In lstForm.Items
            If FormData.FormType = 0 Then
                ISPFound = True
                Exit For
            End If
        Next

        If ISPFound = True Then
            btnAddISPForm.Enabled = False
        Else
            btnAddISPForm.Enabled = True
        End If

        If lstForm.Items.Count > 0 Then lstForm.SelectedIndex = 0

        ChangeMade = True
    End Sub

    Private Sub lstForm_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstForm.DoubleClick
        btnEditForm_Click(Nothing, Nothing)
    End Sub

    Private Sub lstOption_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstOption.SelectedIndexChanged
        If lstOption.SelectedIndex = -1 Then Exit Sub

        Dim ActivePanelName As String

        If lstOption.Text = "Application Update" Then
            ActivePanelName = pnlAppUpdate.Name
            pnlAppUpdate.Visible = True
        ElseIf lstOption.Text = "ISP" Then
            ActivePanelName = pnlISP.Name
            pnlISP.Visible = True
        ElseIf lstOption.Text = "ISP Plan" Then
            ActivePanelName = pnlISPPlan.Name
            pnlISPPlan.Visible = True
        ElseIf lstOption.Text = "Network Card" Then
            ActivePanelName = pnlNIC.Name
            pnlNIC.Visible = True
        ElseIf lstOption.Text = "Update Interval" Then
            ActivePanelName = pnlUpdateInterval.Name
            pnlUpdateInterval.Visible = True
        ElseIf lstOption.Text = "Proxy" Then
            ActivePanelName = pnlProxy.Name
            pnlProxy.Visible = True
        ElseIf lstOption.Text = "Logging" Then
            ActivePanelName = pnlLogging.Name
            pnlLogging.Visible = True
        ElseIf lstOption.Text = "Data Export" Then
            ActivePanelName = pnlDataExport.Name
            pnlDataExport.Visible = True
        ElseIf lstOption.Text = "Image Export" Then
            ActivePanelName = pnlImageExport.Name
            pnlImageExport.Visible = True
        ElseIf lstOption.Text = "Alerts" Then
            ActivePanelName = pnlAlerts.Name
            pnlAlerts.Visible = True
        ElseIf lstOption.Text = "Display" Then
            ActivePanelName = pnlDisplay.Name
            pnlDisplay.Visible = True
        ElseIf lstOption.Text = "UA Icon" Then
            ActivePanelName = pnlUATrayIcon.Name
            pnlUATrayIcon.Visible = True
        ElseIf lstOption.Text = "UA Wallpaper" Then
            ActivePanelName = pnlUAWallpaper.Name
            pnlUAWallpaper.Visible = True
        ElseIf lstOption.Text = "Vista Gadget" Then
            ActivePanelName = pnlVistaGadget.Name
            pnlVistaGadget.Visible = True
        End If

        'go through all panels and hide all but active
        For Each NewObject As Object In Me.Controls
            'check if it's a panel
            If NewObject.GetType Is GetType(Panel) Then
                If CType(NewObject, Panel).Name <> ActivePanelName Then
                    CType(NewObject, Panel).Visible = False
                End If
            End If
        Next
    End Sub

    Private Sub btnApplyWallpaper_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApplyWallpaper.Click
        If SaveCurrentConfiguration() = False Then Exit Sub

        'apply changes
        If UnixDetected() = False Then
            NewShell(Application.StartupPath, Application.StartupPath & Path.DirectorySeparatorChar & "uawallpaper.exe", "", False)
        Else
            NewShell(Application.StartupPath, "mono", "uawallpaper.exe", False)
        End If
    End Sub

    Private Sub lstUsageColourValue_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles lstUsageColourValue.DrawItem
        e.DrawBackground()

        If lstUsageColourValue.Items.Count = 0 Then Exit Sub

        ' Draw the current item text based on the current Font and the custom brush settings.
        e.Graphics.DrawString(CType(lstUsageColourValue.Items(e.Index), UsageColourValue).ToString, e.Font, Brushes.Black, New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height))

        'draw highlight
        Dim NewBrush As New SolidBrush(Color.Black)
        e.Graphics.FillRectangle(NewBrush, e.Bounds.Left + 35, e.Bounds.Top + 1, 30, e.Bounds.Height - 2)
        NewBrush.Dispose()
        NewBrush = New SolidBrush(Color.FromArgb(CInt(CType(lstUsageColourValue.Items(e.Index), UsageColourValue).Value)))
        e.Graphics.FillRectangle(NewBrush, e.Bounds.Left + 36, e.Bounds.Top + 2, 28, e.Bounds.Height - 4)
        NewBrush.Dispose()

        e.DrawFocusRectangle()
    End Sub

    Private Sub BtnFolderDialog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFolderDialog.Click
        Dim fb As New FolderBrowserDialog
        fb.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        Dim RetVal As DialogResult = fb.ShowDialog()
        If RetVal = Windows.Forms.DialogResult.OK Then
            txtExportPath.Text = fb.SelectedPath
        End If
        fb.Dispose()
    End Sub

    Private Sub chkWallpaperEnable_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkWallpaperEnable.CheckedChanged
        If chkWallpaperEnable.Checked = True Then
            chkWallpaperWindowsStartup.Enabled = True
            lstForm.Enabled = True

            'check if there is an ISP entry
            Dim ISPFound As Boolean = False
            For Each FormData As WallpaperFormData In lstForm.Items
                If FormData.FormType = 0 Then
                    ISPFound = True
                    Exit For
                End If
            Next
            If ISPFound = True Then
                btnAddISPForm.Enabled = False
            Else
                btnAddISPForm.Enabled = True
            End If
            btnAddWebForm.Enabled = True
            btnEditForm.Enabled = True
            btnDeleteForm.Enabled = True
            btnApplyWallpaper.Enabled = True
            txtWallpaperUnixCommand.Enabled = True
        Else
            chkWallpaperWindowsStartup.Enabled = False
            lstForm.Enabled = False
            btnAddISPForm.Enabled = False
            btnAddWebForm.Enabled = False
            btnEditForm.Enabled = False
            btnDeleteForm.Enabled = False
            btnApplyWallpaper.Enabled = False
            txtWallpaperUnixCommand.Enabled = False
        End If
    End Sub

    Private Sub btnValidateIcon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidateIcon.Click
        'general tab
        If ValidateGeneral() = False Then Exit Sub

        If ValidateIcon() = False Then Exit Sub

        MessageBox.Show("Icon settings have been validated", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub btnSetImageExportPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetImageExportPath.Click
        Dim fb As New FolderBrowserDialog
        fb.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        Dim RetVal As DialogResult = fb.ShowDialog()
        If RetVal = Windows.Forms.DialogResult.OK Then
            txtExportImagePath.Text = fb.SelectedPath
        End If
        fb.Dispose()
    End Sub

    Private Sub chkExportImage_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkExportImage.CheckedChanged
        If chkExportImage.Checked = True Then
            chkExportHTML.Enabled = True
            chkExportLocalHTMLPath.Enabled = True
            EnableControlChildren(grbExportImagePath)
        Else
            chkExportHTML.Enabled = False
            chkExportLocalHTMLPath.Enabled = False
            DisableControlChildren(grbExportImagePath)
        End If
    End Sub

    Private Sub btnSendTestEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendTestEmail.Click
        If IsValidEmail(txtMailTo.Text) = True Then
            Me.Cursor = Cursors.WaitCursor
            If SendMail(txtMailServer.Text, txtMailTo.Text, "Usage Agent Test Email", "Success!", True) = True Then
                MessageBox.Show("Email Sent!", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            Me.Cursor = Cursors.Default
        Else
            MessageBox.Show("Invalid Email", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub

    Private Sub chkEnableAlerts_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkEnableAlerts.CheckedChanged
        If chkEnableAlerts.Checked = True Then
            EnableControlChildren(grbAlerts)
            If chkAlertEmail.Checked = False Then grbEmail.Enabled = False
        Else
            DisableControlChildren(grbAlerts)
            chkEnableAlerts.Enabled = True
        End If
    End Sub

    Private Sub chkAlertEmail_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkAlertEmail.CheckedChanged
        If chkAlertEmail.Checked = True Then
            grbEmail.Enabled = True
        Else
            grbEmail.Enabled = False
        End If
    End Sub

    Private Sub btnAddAlert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddAlert.Click
        Dim RetVal As Integer = CInt(Val(InputBox("Enter a Percentage value between 1 and 100", "Usage Agent")))
        If RetVal <> 0 Then
            If RetVal > 0 And RetVal <= 100 Then
                lstAlert.Items.Add(RetVal & "%")
                lstAlert.SelectedIndex = lstAlert.Items.IndexOf(RetVal)
                AlertSort(lstAlert)
            Else
                MessageBox.Show("Invalid Value", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
        End If
    End Sub

    Private Sub btnEditAlert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditAlert.Click
        If lstAlert.SelectedIndex = -1 Then Exit Sub

        Dim RetVal As Integer = CInt(Val(InputBox("Enter a Percentage value between 1 and 100", "Usage Agent", Val(lstAlert.SelectedItem.ToString).ToString)))
        If RetVal <> 0 Then
            If RetVal > 0 And RetVal <= 100 Then
                lstAlert.Items(lstAlert.SelectedIndex) = RetVal & "%"
                AlertSort(lstAlert)
            Else
                MessageBox.Show("Invalid Value", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
        End If
    End Sub

    Private Sub btnDeleteAlert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteAlert.Click
        If lstAlert.SelectedIndex = -1 Then Exit Sub

        lstAlert.Items.RemoveAt(lstAlert.SelectedIndex)

        If lstAlert.Items.Count > 0 Then lstAlert.SelectedIndex = 0
    End Sub

    Private Sub lstAlert_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstAlert.DoubleClick
        btnEditAlert_Click(Nothing, Nothing)
    End Sub

    Private Sub btnDefaultAlert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDefaultAlert.Click
        Dim Retval As DialogResult = MessageBox.Show("Are you sure you want to replace the existing alerts with the default values?", "Usage Agent", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If Retval = Windows.Forms.DialogResult.Yes Then
            SetDefaultAlertValue(lstAlert)
            lstAlert.Refresh()
            lstAlert.SelectedIndex = 0
        End If
    End Sub

    Private Sub cboWDM_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboWDM.SelectedIndexChanged
        If cboWDM.Text = "KDE 3.x" Then
            txtWallpaperUnixCommand.Text = "/opt/kde3/bin/dcop"
            txtWallpaperUnixCommandArgs.Text = "kdesktop KBackgroundIface setWallpaper " & AppDataPath & "uawallpaper.png 1"
        ElseIf cboWDM.Text = "Gnome" Then
            txtWallpaperUnixCommand.Text = "/opt/gnome/bin/gconftool-2"
            txtWallpaperUnixCommandArgs.Text = "-t str --set /desktop/gnome/background/picture_options ""centered"" --set /desktop/gnome/background/picture_filename " & AppDataPath & "uawallpaper.png"
        ElseIf cboWDM.Text = "None" Then
            txtWallpaperUnixCommand.Text = ""
            txtWallpaperUnixCommandArgs.Text = ""
        ElseIf cboWDM.Text = "xsetbg" Then
            txtWallpaperUnixCommand.Text = "xsetbg"
            txtWallpaperUnixCommandArgs.Text = AppDataPath & "uawallpaper.png"
        ElseIf cboWDM.Text = "Other" Then
            txtWallpaperUnixCommand.Text = ""
            txtWallpaperUnixCommandArgs.Text = ""
        End If
    End Sub

    Private Sub txtPeakLimit_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPeakLimit.KeyPress
        If Char.IsNumber(e.KeyChar) Or e.KeyChar = Chr(8) Then
            ' Key pressed is number 
            e.Handled = False
        Else
            ' Key pressed is not number 
            e.Handled = True
        End If
    End Sub

    Private Sub txtOffpeakStart_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOffpeakStartHour.KeyPress
        If Char.IsNumber(e.KeyChar) Or e.KeyChar = Chr(8) Then
            ' Key pressed is number 
            e.Handled = False
        Else
            ' Key pressed is not number 
            e.Handled = True
        End If
    End Sub

    Private Sub txtOffpeakEnd_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOffpeakEndHour.KeyPress
        If Char.IsNumber(e.KeyChar) Or e.KeyChar = Chr(8) Then
            ' Key pressed is number 
            e.Handled = False
        Else
            ' Key pressed is not number 
            e.Handled = True
        End If
    End Sub

    Private Sub txtOffpeakLimit_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOffpeakLimit.KeyPress
        If Char.IsNumber(e.KeyChar) Or e.KeyChar = Chr(8) Then
            ' Key pressed is number 
            e.Handled = False
        Else
            ' Key pressed is not number 
            e.Handled = True
        End If
    End Sub

    Private Sub txtExcessRate_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtExcessRate.KeyPress
        If Char.IsNumber(e.KeyChar) Or e.KeyChar = "." Or e.KeyChar = Chr(8) Then
            ' Key pressed is number 
            e.Handled = False
        Else
            ' Key pressed is not number 
            e.Handled = True
        End If
    End Sub

    Private Sub cboOffpeakAvailable_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboOffpeakAvailable.SelectedIndexChanged
        If cboOffpeakAvailable.Text = "Yes" Then
            EnableControlChildren(grbOffpeak)
        Else
            DisableControlChildren(grbOffpeak)
        End If
    End Sub

    Private Sub cboChargesApplicable_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboExcessApplicable.SelectedIndexChanged
        If cboExcessApplicable.Text = "Yes" Then
            EnableControlChildren(grbCharges)
        Else
            DisableControlChildren(grbCharges)
        End If
    End Sub

    Private Sub cboPeakUnlimited_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboPeakUnlimited.SelectedIndexChanged
        If cboPeakUnlimited.Text = "Yes" Then
            txtPeakLimit.Enabled = False
            cboPeakReached.Enabled = False
        Else
            txtPeakLimit.Enabled = True
            cboPeakReached.Enabled = True
        End If
    End Sub

    Private Sub cboOffpeakUnlimited_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboOffpeakUnlimited.SelectedIndexChanged
        If cboOffpeakUnlimited.Text = "Yes" Then
            txtOffpeakLimit.Enabled = False
            cboOffpeakWeekendsUnlimited.Enabled = False
            cboOffpeakReached.Enabled = False
            cboOffpeakAvailableAfterPeakReached.Enabled = False
        Else
            txtOffpeakLimit.Enabled = True
            cboOffpeakWeekendsUnlimited.Enabled = True
            cboOffpeakReached.Enabled = True
            cboOffpeakAvailableAfterPeakReached.Enabled = True
        End If
    End Sub

    Function SaveCurrentConfiguration() As Boolean
        'set values for NewConfigurationData

        'Application Update
        NewConfigurationData.CheckVersionOnStartup = chkCheckVersionOnStartup.Checked
        NewConfigurationData.SendStats = chkSendStats.Checked

        'ISP
        NewConfigurationData.ISPName = cboISP.Text
        NewConfigurationData.Username = txtUsername.Text
        NewConfigurationData.Password = txtPassword.Text
        NewConfigurationData.ISPConnectionType = cboConnectionType.Text
        NewConfigurationData.ISPServiceNo = txtServiceNo.Text

        'ISP Plan
        NewConfigurationData.PeakUnlimited = CBool(cboPeakUnlimited.SelectedIndex)
        NewConfigurationData.PeakUsageLimit = txtPeakLimit.Text
        NewConfigurationData.PeakReached = cboPeakReached.Text
        NewConfigurationData.OffpeakAvailable = CBool(cboOffpeakAvailable.SelectedIndex)
        NewConfigurationData.OffpeakStartHour = Val(txtOffpeakStartHour.Text).ToString
        NewConfigurationData.OffpeakEndHour = Val(txtOffpeakEndHour.Text).ToString
        NewConfigurationData.OffpeakTimeZone = cboOffpeakTimeZone.Text
        NewConfigurationData.OffpeakUnlimited = CBool(cboOffpeakUnlimited.SelectedIndex)
        NewConfigurationData.OffpeakUsageLimit = txtOffpeakLimit.Text
        NewConfigurationData.OffpeakWeekendsUnlimited = CBool(cboOffpeakWeekendsUnlimited.SelectedIndex)
        NewConfigurationData.OffpeakReached = cboOffpeakReached.Text
        NewConfigurationData.OffpeakAvailableAfterPeakReached = CBool(cboOffpeakAvailableAfterPeakReached.SelectedIndex)
        NewConfigurationData.UploadCounted = CBool(cboUploadCounted.SelectedIndex)
        NewConfigurationData.UploadAvailable = CBool(cboUploadAvailable.SelectedIndex)
        NewConfigurationData.WAIXAvailable = CBool(cboWAIXAvailable.SelectedIndex)
        NewConfigurationData.ExcessApplicable = CBool(cboExcessApplicable.SelectedIndex)
        NewConfigurationData.ExcessRate = txtExcessRate.Text
        NewConfigurationData.ExcessMaxCharge = txtExcessMaxCharge.Text
        NewConfigurationData.RolloverDay = cboRolloverDay.Text

        'Network Card
        NewConfigurationData.RetrieveNICData = chkRetrieveNICData.Checked
        NewConfigurationData.NICName = cboNIC.Text

        'Update Interval
        NewConfigurationData.UpdateInterval = CInt(cboUpdateInterval.Text)

        'Proxy
        NewConfigurationData.ProxyConnect = rdbProxy.Checked
        NewConfigurationData.ProxyName = txtProxyName.Text
        NewConfigurationData.ProxyPort = txtProxyPort.Text
        NewConfigurationData.ProxyLogin = txtProxyLogin.Text
        NewConfigurationData.ProxyPassword = txtProxyPassword.Text

        'Logging
        NewConfigurationData.LogEnabled = chkEnableLogging.Checked

        'Data Export
        NewConfigurationData.ExportTextLog = chkExportTextLog.Checked
        NewConfigurationData.ExportDescriptors = chkExportDescriptors.Checked
        NewConfigurationData.ExportNotations = chkExportNotations.Checked
        NewConfigurationData.ExportDownload = chkExportDownload.Checked
        NewConfigurationData.ExportRemaining = chkExportRemaining.Checked
        NewConfigurationData.ExportAverage = chkExportAverage.Checked
        NewConfigurationData.ExportAverageRemaining = chkExportAverageRemaining.Checked
        NewConfigurationData.ExportPlanLimit = chkExportPlanLimit.Checked
        NewConfigurationData.ExportShaped = chkExportShaped.Checked
        NewConfigurationData.ExportTime = chkExportTime.Checked
        NewConfigurationData.ExportUpload = chkExportUpload.Checked
        NewConfigurationData.ExportPath = txtExportPath.Text

        'Image Export
        NewConfigurationData.ExportImage = chkExportImage.Checked
        NewConfigurationData.ExportHTML = chkExportHTML.Checked
        NewConfigurationData.ExportLocalHTMLPath = chkExportLocalHTMLPath.Checked
        NewConfigurationData.ExportImagePath = txtExportImagePath.Text

        'Alerts
        NewConfigurationData.AlertEnable = chkEnableAlerts.Checked
        NewConfigurationData.AlertDialog = chkAlertDialog.Checked
        NewConfigurationData.AlertEmail = chkAlertEmail.Checked
        NewConfigurationData.AlertValue = lstAlert
        NewConfigurationData.AlertMailTo = txtMailTo.Text
        NewConfigurationData.AlertMailServer = txtMailServer.Text

        'Display
        NewConfigurationData.Font = cboFont.Text
        NewConfigurationData.FontSize = CInt(cboFontSize.Text)
        NewConfigurationData.Opacity = (Val(cboOpacity.Text) / 100).ToString
        NewConfigurationData.ShowISPGraph = chkShowISPGraph.Checked
        NewConfigurationData.ShowISPStats = chkShowISPStats.Checked
        NewConfigurationData.ShowNICStats = chkShowNICStats.Checked
        NewConfigurationData.IconISPUsageColourValue = lstUsageColourValue
        NewConfigurationData.ShowBackground = chkShowBackground.Checked
        NewConfigurationData.BackColour = Format(pbxBackgroundColour.BackColor.ToArgb)
        NewConfigurationData.ForeColour = Format(pbxForegroundColour.BackColor.ToArgb)

        'UA Icon
        NewConfigurationData.IconWindowsStartup = chkIconWindowsStartup.Checked
        NewConfigurationData.IconUpdateDelay = CInt(cboUpdateDelay.Text)
        NewConfigurationData.IconStatsShowStartup = chkStatsShowStartup.Checked
        NewConfigurationData.IconShowNICGraph = chkShowNICGraph.Checked
        NewConfigurationData.IconStatsTopmost = chkTopMost.Checked
        NewConfigurationData.IconStartX = CInt(txtXPos.Text)
        NewConfigurationData.IconStartY = CInt(txtYPos.Text)
        NewConfigurationData.IconNICCapacityDown = CInt(txtCapacityDown.Text)
        NewConfigurationData.IconNICCapacityUp = CInt(txtCapacityUp.Text)
        NewConfigurationData.IconTrayISPUsage = chkIconISPUsage.Checked
        NewConfigurationData.IconTrayISPColour = chkIconISPColour.Checked
        NewConfigurationData.IconTrayNICGraph = chkIconNicGraph.Checked

        'UA Wallpaper
        NewConfigurationData.WallpaperEnable = chkWallpaperEnable.Checked
        NewConfigurationData.WallpaperWindowsStartup = chkWallpaperWindowsStartup.Checked
        'go through each form and save
        NewConfigurationData.WallpaperFormList.Clear()
        For Each NewFormData As WallpaperFormData In lstForm.Items
            NewConfigurationData.WallpaperFormList.Add(NewFormData)
        Next
        NewConfigurationData.WallpaperUnixCommand = txtWallpaperUnixCommand.Text
        NewConfigurationData.WallpaperUnixCommandArgs = txtWallpaperUnixCommandArgs.Text

        'vista gadget
        NewConfigurationData.VistaGadgetEnable = chkEnableVistaGadget.Checked

        If NewConfigurationData.VistaGadgetEnable = True Then
            'only add gadget if ISP settings are valid
            If ValidateGeneral(False) = False Then Exit Function

            'create image file
            CreateImageFile(NewConfigurationData, ISPReturnData)

            Dim FormSize As Point = CalculateFormSize(NewConfigurationData, ISPReturnData)
            SaveCurrentConfiguration = SaveConfiguration(NewConfigurationData, False, FormSize.X, FormSize.Y)
        Else
            SaveCurrentConfiguration = SaveConfiguration(NewConfigurationData, False)
        End If

    End Function

    Private Sub cboUploadCounted_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboUploadCounted.SelectedIndexChanged
        If cboUploadCounted.Text = "Yes" Then
            cboUploadAvailable.Enabled = True
        Else
            cboUploadAvailable.Enabled = False
        End If
    End Sub

    Private Sub txtRolloverDate_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If Char.IsNumber(e.KeyChar) Or e.KeyChar = Chr(8) Then
            ' Key pressed is number 
            e.Handled = False
        Else
            ' Key pressed is not number 
            e.Handled = True
        End If
    End Sub

    Private Sub cboFont_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFont.SelectedIndexChanged
        Try
            lblFontPreview.Font = New Font(cboFont.Text, CSng(CInt(cboFontSize.Text) * (96 / GetDPI())), FontStyle.Regular)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cboFontSize_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFontSize.SelectedIndexChanged
        Try
            lblFontPreview.Font = New Font(cboFont.Text, CSng(CInt(cboFontSize.Text) * (96 / GetDPI())), FontStyle.Regular)
        Catch ex As Exception

        End Try
    End Sub

End Class

